﻿using Microsoft.AspNetCore.Http;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SH.Common.Helper
{
    public static class QiniuHelper
    {
        public static HttpResult UploadFile(IFormFile file)
        {
            //请到官网申请七牛云账号、秘钥
            var accessKey = "oq6ximPShSS-s73QUzC_Y80Js2iZIrQkuSy4VvZo";
            var secretKey = "uUC9zsSMC9Jvw7jDIaoU-3vGJqX6pWhBUZ6ficdi";
            #region 上传到七牛云
            //保存到七牛云上的文件目录
            string saveKey = "图片上传测试/" + file.FileName;
            // 存储空间名
            string Bucket = "nkyholtel";
            // 设置上传策略
            //可以自行查看官网SDK:https://developer.qiniu.com/kodo/1237/csharp
            PutPolicy putPolicy = new PutPolicy();
            // 设置要上传的目标空间
            putPolicy.Scope = Bucket;

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;

            // 上传策略有效期(对应于生成的凭证的有效期，单位:秒)
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 100;

            // 生成上传token
            Mac mac = new Mac(accessKey, secretKey);
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            Config config = new Config();
            // 设置上传区域  [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
            config.Zone = Zone.ZONE_CN_North;
            // 设置 http 或者 https 上传
            config.UseHttps = true;
            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U512K;

            //图片上传到七牛云
            FormUploader target = new FormUploader(config);
            HttpResult result = target.UploadStream(file.OpenReadStream(), saveKey, token, null);
            return result;


            #endregion
        }
    }
}
